import { FC, useEffect, useState } from 'react';
import { SEPARATOR_HOTKEY } from './const';
import { keyCodeFormat } from './utils';
import { Input } from 'antd';

export interface IProps {
  value?: string;
  placeholder?: string;
  hidden?: boolean;
  disabled?: boolean;
  onChange?: (value: string) => void;
  name?: string;
}

const HotkeyInput: FC<IProps> = ({
  value,
  placeholder,
  onChange: onChange,
  hidden,
  disabled,
  name,
}) => {
  const [hotkeySet, setHotkeySet] = useState<string[]>([]);

  useEffect(() => {
    setHotkeySet(Array.from(new Set((value?.split(SEPARATOR_HOTKEY).filter(item => item) || []))));
  }, [value]);

  const _value = hotkeySet.join(SEPARATOR_HOTKEY);

  useEffect(() => {
    onChange?.(_value);
  }, [_value]);

  return (
    <Input
      hidden={hidden}
      className="hotkey-input"
      allowClear
      name={name}
      disabled={disabled}
      type="text"
      value={_value}
      placeholder={placeholder}
      onChange={(e) => {
        if (e.type === 'click' && !e.target.value) {
          setHotkeySet([]);
        }
      }}
      onKeyDown={(e) => {
        const mapKey = keyCodeFormat(e.code);
        switch (mapKey) {
          case 'Backspace':
            setHotkeySet(prev => prev.slice(0, -1));
            break;
          case 'Unidentified':
            // 不知道哪里来的
            break;
          default:
            setHotkeySet(prev => Array.from(new Set([...prev, mapKey])));
        }
      }}
    />
  );
}

export default HotkeyInput;